import React, {Component} from 'react';

import {
    View,
    Text,
    ListView,
    StyleSheet,
    RefreshControl,
    DeviceEventEmitter
} from 'react-native';
import RespositoryCell from '../../common/RepositoryCell';
import {THEMECOLOR} from "../../config/main";
import DataRepository, {FLAG_STORAGE} from "../../expand/Dao/DataRepository";
import ProjectModel from '../../expand/Dao/ProjectModel'
import FavoriteDao from "../../expand/Dao/FavoriteDao";
import Util from "../../util/Util"

export default class PopularTab extends Component {

    constructor(props) {
        super(props)
        this.state = {
            isLoading   : false,
            keyword     : '',
            dataSource  : new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}),
            favoriteKeys: []
        }
        this.result = []
        this.favoriteDao = new FavoriteDao(FLAG_STORAGE.flag_popular)
    }

    componentDidMount() {
        this.onLoad()
    }

    flushFavoriteState() {
        let result = this.result
        //console.warn(5)
        let projectModels = []
        for (let i = 0, l = result.items.length; i < l; i++) {
            projectModels.push(new ProjectModel(result.items[i], Util.checkFavorite(result.items[i], this.state.favoriteKeys)))
        }
        this.setState({
            dataSource: this.state.dataSource.cloneWithRows(projectModels),
            isLoading : false
        })
    }

    onLoad() {
        this.setState({
            isLoading: true
        })
        let url = `https://api.github.com/search/repositories?q=${this.props.keyword}&sort=stars`
        this.DataRepository = new DataRepository(FLAG_STORAGE.flag_popular)
        this.DataRepository.fetch(url)
            .then(result => {
                if (result && result.update_time && !this.DataRepository.checkData(result.update_time)) {
                    DeviceEventEmitter.emit('showToast', '数据过时')
                    return this.DataRepository.fetchNetRepository(url)
                } else {
                    //console.warn(1)
                    this.result = result
                    //console.warn(2)
                    this.getFavorite()
                    DeviceEventEmitter.emit('showToast', '显示缓存数据')
                }
            })
            .then(result => {
                this.result = result
                this.getFavorite()
                DeviceEventEmitter.emit('showToast', '显示网络数据')
            })
            .catch(e => {
                this.setState({
                    isLoading: false
                })
            })
    }

    getFavorite() {
        this.favoriteDao.getFavoriteKeys()
            .then((result) => {
            //console.warn(3)
                this.state.favoriteKeys = result
                this.flushFavoriteState()
            })
            .catch((error) => {
            //console.warn(error)
                this.flushFavoriteState()
            })
    }

    onFavorite(item, isFavorite) {
        this.favoriteDao.updataFavorite(item.id.toString(), isFavorite)
    }

    render() {
        return (
            <View style={{flex: 1}}>
                <ListView
                    dataSource={this.state.dataSource}
                    renderRow={(projectModel) => <RespositoryCell projectModel={projectModel} {...this.props}
                                                                  onFavorite={(item, isFavorite) => {
                                                                      this.onFavorite(item, isFavorite)
                                                                  }}/>}
                    refreshControl={<RefreshControl
                        refreshing={this.state.isLoading}
                        onRefresh={() => {
                            this.onLoad()
                        }}
                        colors={[THEMECOLOR]}
                        tintColor={THEMECOLOR}
                        title='加载中...'
                        titleColor={THEMECOLOR}
                    />}
                />
            </View>
        )
    }
}

const styles = StyleSheet.create({})